package com.flca.frw.util;

import java.io.File;
import java.net.URL;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonHelper {

	public static ObjectMapper om = new ObjectMapper();

	public static Logger logger = LoggerFactory.getLogger(JsonHelper.class);
	
	private JsonHelper() {
	}

	public static void saveObject(Object aSource, String aFilename) 
	{
		try {
			String json = om.writeValueAsString(aSource);
			FileUtils.saveFile(aFilename, json);
		} catch (Exception e) {
			logger.error("error saving object to json " + e);
			throw new RuntimeException(e);
		}
	}
	
	public static void saveObject(Object aSource, File aFile) 
	{
		try {
			String json = om.writeValueAsString(aSource);
			FileUtils.saveFile(aFile, json);
		} catch (Exception e) {
			logger.error("error saving object to json " + e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * Create an object given a xstream file
	 * @param aFilename
	 * @return
	 */
	public static Object readObject(String aFilename, Class<?> aClass) 
	{
		return readObject(new File(aFilename), aClass);
	}

	public static Object readObject(File aFile, Class<?> aClass) 
	{
		try {
			URL url = FileUtils.getExistingUrl(aFile.getPath());
			if (url != null) {
				String json = FileUtils.readFile(url);
				return om.readValue(json, aClass);
			} else {
				logger.error("file  " + aFile.getPath() + " could not be found");
				return null;
			}
		} catch (Exception e) {
			logger.error("error reading json object " + e);
			return null;
		}
	}

}
